﻿#region MIT
/*
Engine Of Evermore (http://code.google.com/p/engineofevermore/)
Copyright (c) 2008, 2009 Michael Woerister

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using AgateLib.DisplayLib;
using EngineOfEvermore.Common;

namespace EngineOfEvermore.Imaging.AgateImplementation
{
    public class AgateImageMapFrame : ImageMapFrame
    {
        #region Fields
        bool _disposed;
        #endregion

        #region Properties
        public Surface Surface { get; private set; }
        #endregion

        #region Constructors
        public AgateImageMapFrame( Surface surface, Rectangle originalArea,
            Rectangle originalNonTransparentArea, Rectangle convertedArea ) :
            base( false, originalArea, originalNonTransparentArea, convertedArea )
        {
            this.Surface = surface;
        }

        private AgateImageMapFrame( Rectangle originalArea ) :
            base( true, originalArea, Rectangle.Empty, Rectangle.Empty )
        {
        }

        public static AgateImageMapFrame CreateEmptyFrame( Rectangle originalArea )
        {
            return new AgateImageMapFrame( originalArea );
        }
        #endregion

        #region Public Methods

        public override void DrawFrame( Vector2d position, Vector2d scale, Color color,
            bool flipX, bool flipY )
        {
            RectangleF destRect = new RectangleF(
                position.X - ( this.OriginalArea.Width / 2 ) * scale.X,
                position.Y - ( this.OriginalArea.Height / 2 ) * scale.Y,
                this.OriginalArea.Width * scale.X,
                this.OriginalArea.Height * scale.Y
                );

            this.DrawFrameInRectangle( destRect, color, flipX, flipY );
        }

        public override void DrawFrameInRectangle( RectangleF position, Color color, bool flipX,
            bool flipY )
        {
            if ( this.IsEmpty )
                return;

            var finalDestRect = new AgateLib.Geometry.RectangleF();

            if ( !flipX )
            {
                finalDestRect.X = position.X + this.RelativeOffset.X * position.Width;
                finalDestRect.Width = position.Width * this.RelativeSize.X;
            }
            else
            {
                finalDestRect.X = position.X + position.Width -
                    this.RelativeOffset.X * position.Width;
                finalDestRect.Width = -position.Width * this.RelativeSize.X;
            }

            if ( !flipY )
            {
                finalDestRect.Y = position.Y + this.RelativeOffset.Y * position.Height;
                finalDestRect.Height = position.Height * this.RelativeSize.Y;
            }
            else
            {
                finalDestRect.Y = position.Y + position.Height -
                    this.RelativeOffset.Y * position.Height;
                finalDestRect.Height = -position.Height * this.RelativeSize.Y;
            }

            this.Surface.InterpolationHint = AgateLib.DisplayLib.InterpolationMode.Fastest;
            this.Surface.Color = AgateLib.Geometry.Color.White;
            this.Surface.Impl.Draw( _getTextureCoordinatesF(), finalDestRect );
        }

        public override void DrawFrameRotated( Vector2d center, float rotation,
            Vector2d scale, Color color, bool flipX, bool flipY )
        {
            if ( this.IsEmpty )
                return;

            var renderOffset = _getAbsoluteRenderOffset( this.RelativeArea, scale, flipX, flipY );

            var xUnit = new Vector2d( 1, 0 ).RotatedBy( rotation );
            var yUnit = new Vector2d( 0, 1 ).RotatedBy( rotation );

            var renderUpperLeft = _getOriginalUpperLeft( center, scale, xUnit, yUnit )
                + xUnit * renderOffset.X + yUnit * renderOffset.Y;

            var srcRect = _getTextureCoordinates();

            this.Surface.InterpolationHint = AgateLib.DisplayLib.InterpolationMode.Fastest;
            this.Surface.RotationAngle = -Util.DegToRad( rotation );
            this.Surface.SetScale( flipX ? -scale.X : scale.X, flipY ? -scale.Y : scale.Y );
            this.Surface.Color = AgateLib.WinForms.Interop.Convert( color );

            this.Surface.DisplayAlignment = AgateLib.DisplayLib.OriginAlignment.TopLeft;
            this.Surface.Draw( renderUpperLeft.X, renderUpperLeft.Y, srcRect, 0, 0 );
        }

        public override void DrawFrameClippedAndRotated( Vector2d center, float rotation, Vector2d scale,
            bool flipX, bool flipY, Color color, RectangleF clipArea )
        {
            if ( this.IsEmpty )
                return;

            RectangleF intersection = _getIntersection( clipArea );

            if ( intersection.IsEmpty )
                return;

            var renderOffset = _getAbsoluteRenderOffset( intersection, scale, flipX, flipY );

            Vector2d xUnit = new Vector2d( 1, 0 ).RotatedBy( rotation );
            Vector2d yUnit = new Vector2d( 0, 1 ).RotatedBy( rotation );

            var renderUpperLeft = _getOriginalUpperLeft( center, scale, xUnit, yUnit )
                + xUnit * renderOffset.X + yUnit * renderOffset.Y;

            var srcRect = _getTextureCoordinates( clipArea );

            this.Surface.InterpolationHint = AgateLib.DisplayLib.InterpolationMode.Fastest;
            this.Surface.RotationAngle = -Util.DegToRad( rotation );
            this.Surface.SetScale( flipX ? -scale.X : scale.X, flipY ? -scale.Y : scale.Y );
            this.Surface.Color = AgateLib.WinForms.Interop.Convert( color );

            this.Surface.DisplayAlignment = AgateLib.DisplayLib.OriginAlignment.TopLeft;
            this.Surface.Draw( renderUpperLeft.X, renderUpperLeft.Y, srcRect, 0, 0 );
        }
        #endregion

        #region Private Helper Methods
        private float _relativeToAbsoluteX( float x )
        {
            return x * this.Width;
        }

        private float _relativeToAbsoluteY( float y )
        {
            return y * this.Height;
        }

        private Rectangle _relativeToAbsolute( RectangleF rect )
        {
            return new Rectangle(
                (int) _relativeToAbsoluteX( rect.X ),
                (int) _relativeToAbsoluteY( rect.Y ),
                (int) _relativeToAbsoluteX( rect.Width ),
                (int) _relativeToAbsoluteY( rect.Height )
                );
        }

        private Vector2d _getOriginalUpperLeft( Vector2d position, Vector2d scale, Vector2d xUnit,
            Vector2d yUnit )
        {
            return position - xUnit * ( 0.5f * this.Width * scale.X )
                            - yUnit * ( 0.5f * this.Height * scale.Y );
        }

        private Vector2d _getAbsoluteRenderOffset( RectangleF intersection, Vector2d scale, bool flipX,
            bool flipY )
        {
            Vector2d result = new Vector2d();

            if ( !flipX )
            {
                result.X = intersection.X * this.Width * scale.X;
            }
            else
            {
                result.X = this.Width;
                result.X -= _relativeToAbsoluteX( intersection.X + intersection.Width );
                result.X *= scale.X;
            }

            if ( !flipY )
            {
                result.Y = intersection.Y * this.Height * scale.Y;
            }
            else
            {
                result.Y = this.Height;
                result.Y -= _relativeToAbsoluteY( intersection.Y + intersection.Height );
                result.Y *= scale.Y;
            }

            return result;
        }

        private RectangleF _getIntersection( RectangleF clipArea )
        {
            RectangleF intersection = this.RelativeArea;
            intersection.Intersect( clipArea );
            return intersection;
        }

        private AgateLib.Geometry.Rectangle _getTextureCoordinates()
        {
            return new AgateLib.Geometry.Rectangle(
                this.ConvertedArea.X,
                this.ConvertedArea.Y,
                this.ConvertedArea.Width,
                this.ConvertedArea.Height
                );
        }

        private AgateLib.Geometry.RectangleF _getTextureCoordinatesF()
        {
            return new AgateLib.Geometry.RectangleF(
                this.ConvertedArea.X,
                this.ConvertedArea.Y,
                this.ConvertedArea.Width,
                this.ConvertedArea.Height
                );
        }

        private AgateLib.Geometry.Rectangle _getTextureCoordinates( RectangleF clipArea )
        {
            AgateLib.Geometry.Rectangle result = new AgateLib.Geometry.Rectangle();

            // Calculate texCoordLeft
            if ( clipArea.X <= this.RelativeOffset.X )
            {
                result.X = this.ConvertedArea.Left;
            }
            else
            {
                float f = ( ( clipArea.X - this.RelativeOffset.X ) / this.RelativeSize.X );
                result.X = (int) ( ( f * this.ConvertedArea.Width ) + this.ConvertedArea.X );
            }

            int texCoordRight;

            // Calculate texCoordRight
            if ( clipArea.Right >= this.RelativeOffset.X + this.RelativeSize.X )
            {
                texCoordRight = this.ConvertedArea.Right;
            }
            else
            {
                float f = ( ( clipArea.Right - this.RelativeOffset.X ) / this.RelativeSize.X );
                texCoordRight = (int) ( ( f * this.ConvertedArea.Width ) + this.ConvertedArea.X );
            }
            result.Width = texCoordRight - result.X + 1;

            // Calculate texCoordTop
            if ( clipArea.Y <= this.RelativeOffset.Y )
            {
                result.Y = this.ConvertedArea.Top;
            }
            else
            {
                float f = ( ( clipArea.Y - this.RelativeOffset.Y ) / this.RelativeSize.Y );
                result.Y = (int) ( ( f * this.ConvertedArea.Height ) + this.ConvertedArea.Y );
            }


            int texcoordBottom;
            // Calculate texCoordBottom
            if ( clipArea.Bottom >= this.RelativeOffset.Y + this.RelativeSize.Y )
            {
                texcoordBottom = this.ConvertedArea.Bottom;
            }
            else
            {
                float f = ( ( clipArea.Bottom - this.RelativeOffset.Y ) / this.RelativeSize.Y );
                texcoordBottom = (int) ( ( f * this.ConvertedArea.Height ) + this.ConvertedArea.Y );
            }

            result.Height = texcoordBottom - result.Y + 1;

            return result;
        }
        #endregion

        #region IDisposable Members

        protected override void _dispose( bool disposing )
        {
            if ( !_disposed )
            {
                if ( disposing )
                {
                    if ( this.Surface != null && !this.Surface.IsDisposed )
                    {
                        this.Surface.Dispose();
                        this.Surface = null;
                    }
                }

                _disposed = true;
            }
        }
        #endregion
    }
}
